package com.yunshipei.ui.view;

import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.enterplorer.R;

import java.io.File;
import java.io.IOException;

//import io.rong.imkit.RLog;

import io.rong.common.RLog;
import io.rong.imkit.RongContext;

/**
 * Created by cike on 15-11-18.
 */
public class TouchTextView extends TextView implements Handler.Callback {
    private String TAG = TouchTextView.class.getSimpleName();
    private OnMyTouchEvent onMyTouchEvent = null;
    private Handler mHandler;
    private PopupWindow mPopWindow;
    private float lastTouchY;
    private long mVoiceLength;
    private ImageView mIcon;
    private TextView mMessage;
    private int mStatus = MSG_NORMAL;
    private AudioManager mAudioManager;
    private Uri mCurrentRecUri;
    private Context context;
    private ProgressBar progressBar;

    private static final int MSG_NORMAL = 0;
    private static final int MSG_SEC = 1;
    private static final int MSG_CANCEL = 2;
    private static final int MSG_SHORT = 7;
    private static final int MSG_SAMPLING = 3;
    private static final int MSG_COMPLETE = 5;
    private static final int MSG_READY = 4;
    private static final int MSG_HANDLE = 8;
    private MediaRecorder mMediaRecorder;
    private boolean getVolumeStatus = true;
    private int currentVoiceDb = 0;

    public TouchTextView(Context context) {
        super(context);
    }

    public TouchTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        mHandler = new Handler(this);
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mMediaRecorder = new MediaRecorder();
    }

    public TouchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        super.onTouchEvent(ev);
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                onMyTouchEvent.actionDownHandle();
                lastTouchY = ev.getY();
                mHandler.obtainMessage(MSG_READY, this.getRootView()).sendToTarget();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mHandler.obtainMessage(MSG_HANDLE).sendToTarget();
                onMyTouchEvent.actionUpHandle();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            default:
                break;
        }
        return true;
    }


    public void setOnMyTouchEvent(OnMyTouchEvent onMyTouchEvent) {
        this.onMyTouchEvent = onMyTouchEvent;
    }

    public interface OnMyTouchEvent {
        //按钮点击
        void actionDownHandle();

        //按钮释放
        void actionUpHandle();
    }

    //    识别结束
    public void discornStop() {
        mHandler.obtainMessage(MSG_COMPLETE).sendToTarget();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //准备
            case MSG_READY:
                if (mPopWindow == null) {
                    LayoutInflater flate = LayoutInflater.from(getContext());
                    View view = flate.inflate(R.layout.notifi_voice_popup_layout, null);

                    mIcon = (ImageView) view.findViewById(R.id.notifi_icon);
                    mMessage = (TextView) view.findViewById(R.id.notifi_message);
                    progressBar = (ProgressBar) view.findViewById(R.id.process_voice);
                    mPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    View parent = (View) msg.obj;
                    mPopWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
                    mPopWindow.setFocusable(true);
                    mPopWindow.setOutsideTouchable(false);
                    mPopWindow.setTouchable(false);
                } else {
                    Log.e("mPopWindow", "mPopWindow not is null");
                }

                startRec();
                mStatus = MSG_READY;
                mVoiceLength = SystemClock.elapsedRealtime();
                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SAMPLING),
                        500);

                mMessage.setText("");
                mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_1);
                mMessage.setBackgroundColor(Color.TRANSPARENT);

                break;
            case MSG_SAMPLING:
                int db = 0;
                Bundle bundle = msg.getData();
                db = bundle.getInt("voiceDb");
                switch (db) {
                    case 0:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_1);
                        break;
                    case 1:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_2);
                        break;
                    case 2:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_3);
                        break;
                    case 3:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_4);
                        break;
                    case 4:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_5);
                        break;
                    case 5:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_6);
                        break;
                    case 6:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_7);
                        break;
                    default:
                        mIcon.setImageResource(io.rong.imkit.R.drawable.rc_ic_volume_8);
                        break;
                }
                break;

            case MSG_COMPLETE:
                RLog.e( "handleMessage", "----MSG_COMPLETE-----");
                mHandler.removeMessages(MSG_READY);
                mHandler.removeMessages(MSG_SEC);
                mHandler.removeMessages(MSG_CANCEL);
                if (mPopWindow != null && mPopWindow.isShowing()) {
                    mPopWindow.dismiss();
                    mPopWindow = null;
                }
                break;
            case MSG_HANDLE:
                /**
                 * 录音结束，识别处理
                 */
                mIcon.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                mMessage.setText("正在识别中..");
                mHandler.removeMessages(MSG_SAMPLING);
                stopRec();
                break;
            default:
                break;

        }
        return false;
    }

    public class VoiceException extends RuntimeException {
        public VoiceException(Throwable e) {
            super(e);
        }

    }

    public void setCurrentVoiceDb(int i) {
        this.getVolumeStatus = false;
        this.currentVoiceDb = i;
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putInt("voiceDb", i);
        message.setData(bundle);
        message.what = MSG_SAMPLING;
        mHandler.sendMessage(message);
//        mHandler.obtainMessage(MSG_SAMPLING).sendToTarget();
    }

    public int getCurrentVoice() {
        Log.e("currentVoice", "" + currentVoiceDb);
        return this.currentVoiceDb;
    }


    public int getCurrentVoiceDb() {
        if (mMediaRecorder == null) {
            Log.e("TouchTextView", "mMediaRecorder is null");
            return 0;
        } else {
            return mMediaRecorder.getMaxAmplitude() / 600;
        }
    }

    public void startRec() throws VoiceException {

        mAudioManager.setMode(AudioManager.MODE_NORMAL);
        try {
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mCurrentRecUri = Uri.fromFile(new File(context.getFilesDir().getParentFile(), "temp.voice"));
            mMediaRecorder.setOutputFile(mCurrentRecUri.getPath());

            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (RuntimeException ex) {
            if (mMediaRecorder != null) {
                mMediaRecorder.reset();
                mMediaRecorder.release();
            }
            Log.e("RunTimeException", ex.toString());
            mMediaRecorder = null;
            ex.printStackTrace();
        } catch (IOException e) {
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
            e.printStackTrace();
        }
        mStatus = MSG_READY;
    }


    public void stopRec() throws VoiceException {
        boolean isError = false;
        if (mMediaRecorder == null)
            return;
        try {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        if (isError) {
            Toast.makeText(RongContext.getInstance(), RongContext.getInstance().getResources().getString(io.rong.imkit.R.string.rc_voice_failure), Toast.LENGTH_SHORT).show();
        }
        mStatus = MSG_NORMAL;

    }
}
